package com.learn.mvc.exception;

import com.learn.mvc.util.MVCUtil;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    public String resolveNullPointerException(Exception e, Model model) {
        model.addAttribute("exception", e);
        return "error-nullPointer";
    }

    @ExceptionHandler(Exception.class)
    public String resolveArrayIndexOutOfBoundsException(Exception e, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {

        if(MVCUtil.judgeRequestType(request)) {
            response.setContentType("text/html;charset=utf-8");

            response.getWriter().print(e.getMessage());

            return null;
        }

        model.addAttribute("exception", e);
        return "error-exception";

    }


}
